import Store from '@/store'
import {
	jumpPage as jump
} from "@/utils/route/route"
import {
	useGetUserInfo,
	useUpdUserPerfect
} from './useUser'
import {
	login as apiLogin,
	getRoutes as apiGetRoutes
} from "@/api/Interface/login"
import BasicConfig from "@/utils/config"
import {
	RoutesPathConfig
} from "@/utils/path.config"


export const useHandshakeLogin = async () => {
	const isLogin = Store.state.login.isLogin
	if (!isLogin) {
		uni.navigateTo({
			url: "/pages/login/login"
		})
		return;
	}
}

const _initJump = () => {
	const perfect = Store.state.user.perfect;
	const routes = Store.state.user.tabbarRoutes;
	let index = 0;
	if (!perfect) {
		index = routes.findIndex(f => f.key === "my");
		index = index > 0 ? index : 0
	}
	console.log("登录", routes[index].path);
	jump({
		to: routes[index].path ?? "",
		mode: "switchTab",
		login: false
	})
}

const _saveLogin = (res) => {
	// 用户登录状态设置
	Store.commit('login/SET_USER_LOGINSTATUS', true);
	Store.commit('user/SET_USERID', res.user[0]?.user_id);
	Store.commit('user/SET_TOKEN', res.token);
	useUpdUserPerfect(res.bs)
}

export const useHandleLogin = async (param) => {
	// return new Promise((resolve,reject)=>{

	// })
	try {
		await useLogin(param);
		await useGetUserInfo();
		await useGetRoutes();
		_initJump();
		return Promise.resolve(200)
	} catch (e) {
		//TODO handle the exception
		return Promise.resolve(400)
	}
}

export const useLogin = async (param) => {
	return new Promise(async (resolve, reject) => {
		// 发送登录请求
		await apiLogin(param).then(res => {
			if (res.code === 200 && res?.data?.code === 200) {
				_saveLogin(res)
				resolve(res)
			} else {
				BasicConfig.toast(res?.data?.code !== 200 ? res?.data?.msg : res.msg)
				reject(res)
			}
		}).catch(err => {
			reject(err)
			uni.showToast({
				title: err.data.msg || '请求异常'
			})
		})
	})
}

export const useGetRoutes = async () => {
	return new Promise(async (resolve, reject) => {
		// 发送登录请求
		await apiGetRoutes({
			roleKey: Store.state.user.userInfo.roleId
		}).then(res => {
			console.log("获取路由", res, RoutesPathConfig);
			if (res.code === 200) {
				res.data.map(m => m.path = RoutesPathConfig[m.key])
				Store.commit('user/SET_ROUTES', res.data)
			} else {
				BasicConfig.toast(res.msg)
			}
			resolve(res)
		}).catch(err => {
			reject(err)
			uni.showToast({
				title: err.data.msg || '请求异常'
			})
		})
	});
}

export const useLogout = () => {
	Store.commit('login/LOG_OUT')
	Store.commit('user/INIT_USER', null)
}